#############################################################################
#
# Just Another Package Builder http://code.google.com/p/japb
# (c)2011 Alexander Galanin
#
# Mercurial VCS support
#
# $Id$
#
#############################################################################

package require Tcl 8.5
package require japb::filenode

package provide japb::hg 1.0

namespace eval japb {

namespace export hg

namespace eval hg {

namespace import ::japb::filenode

# Create an unversioned archive of a repository revision
# @param type archive type (files, zip, tgz, etc...)
# @param name directory prefix for files in archive
# @param args extra mercurial parameters
# @return file node of generated archive
proc archive {type name args} {
    if {$type eq "files"} {
        set outname $name
        set prefixArgs {}
    } else {
        set outname $name.$type
        set prefixArgs [list -p $name]
    }
    set outdata [filenode mkfile $outname]
    exec hg archive -t $type {*}$prefixArgs [filenode path $outdata] {*}$args
    return $outdata
}

# Detect that current directory are located under Mercurial VCS and hg
# executable is in PATH
# @param repo repository location
proc isUnderVcs {{repo .}} {
    expr {[file exists [file join $repo .hg]] && [auto_execok hg] ne ""}
}

# Detect version hash (from hg -i or from archive info)
# @param repo repository location
# @return version hash (12-digit hex)
proc versionHash {{repo .}} {
    if {[isUnderVcs $repo]} {
        set hash [exec hg id -i -R $repo]
    } else {
        if {![file readable $repo/.hg_archival.txt]} {
            error "Unable to determine mercurial changeset!"
        }

        set f [open $repo/.hg_archival.txt]
        set data [read $f]
        close $f

        if {![regexp {node: (.{12,12})} $data _ hash]} {
            error "Unable to determine VCS hash"
        }
    }
    return $hash
}

# Generate file node with mercurial changeset
proc versionHashFile {filename} {
    set hashFile [filenode mkfile $filename]
    set f [open [filenode path $hashFile] w]
    puts $f [versionHash]
    close $f

    return $hashFile
}

# List checkouts
# @param types file states (see hg help status)
# @param args extra mercurial arguments
proc listCheckouts {{types durman} args} {
    exec hg status -$types {*}$args
}

namespace export \
    archive \
    isUnderVcs \
    versionHash \
    versionHashFile \
    listCheckouts
namespace ensemble create
}
}
